package com.mco.service;

import com.mco.entity.Customer;
import com.mco.entity.User;
import com.mco.mapepr.CustomerMapper;
import com.mco.mapepr.UserMapper;
import com.mco.utils.bloomfilter.CheckUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.Key;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现
 *
 * @author ：liao.wei
 * @date ：2023/9/14 21:13
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CustomerService {
	
	public static final String CACHE_KEY_CUSTOMER = "customer:";
	
	public static final String WHITE_CACHE_KEY_CUSTOMER = "white_list_customer";
	
	private final CustomerMapper customerMapper;
	
	private final RedisTemplate redisTemplate;
	
	private final CheckUtil checkUtil;
	
	/**
	 * 写操作
	 *
	 * @param customer
	 * @author liaowei
	 * @date 2023/9/23 15:59
	 */
	public void addCustomer(Customer customer) {
		int i = customerMapper.insert(customer);
		if (i > 0) {
			//查询数据写入缓存
			customer = customerMapper.selectById(customer.getId());
			// 缓存key
			String key = CACHE_KEY_CUSTOMER + customer.getId();
			//写入redis
			redisTemplate.opsForValue().set(key, customer);
		}
	}
	
	public void updateCustomer(Customer customer) {
		customerMapper.updateById(customer);
	}
	
	public Customer find(Long id) {
		//key
		String key = CACHE_KEY_CUSTOMER + id;
		//-------------加入布隆过滤器---------------
		if (!checkUtil.checkWithBloomFilter(WHITE_CACHE_KEY_CUSTOMER, key)) {
			log.info("无此customer");
			return null;
		}
		log.info("进入");
		//---------------------------
		Customer customer = (Customer) redisTemplate.opsForValue().get(key);
		// 先查缓存
		if (Objects.nonNull(customer)) {
			return customer;
		}
		//查数据库
		customer = customerMapper.selectById(id);
		
		if (Objects.nonNull(customer)) {
			// 回写redis
			redisTemplate.opsForValue().set(CACHE_KEY_CUSTOMER + customer.getId(), customer);
		}
		return customer;
	}
}
